using System.Reflection;
using IGeekFan.AspNetCore.Knife4jUI;
using Microsoft.OpenApi.Models;

namespace Ellwood.Manage.MentApi.Utility.SwaggerExt;

/// <summary>
/// swagger扩展
/// </summary>
public static class CustomSwaggerExt
{

    /// <summary>
    /// swagger 自定义配置
    /// </summary>
    /// <param name="builder"></param>
    public static void AddSwaggerExt(this WebApplicationBuilder builder)
    {
        // 配置Knife4UI
        builder.Services.AddSwaggerGen(option =>
        {
            typeof(ApiVersion).GetEnumNames().ToList().ForEach(version =>
            {
                var contact = new OpenApiContact();
                contact.Name = "Ellwood111";

                option.SwaggerDoc(version, new OpenApiInfo()
                {
                    Title = $"Ellwood Management API {version}",
                    Version = version,
                    TermsOfService = new Uri("https://www.ellwood.com"),
                    Contact = contact,
                    Description = $"Ellwood Management API {version}"
                });
            });

            // 配置 Swagger 生成的 XML 文档 【这样可是接口的注释展示出来】
            // 在项目属性中启用 XML 文档生成。右键点击项目，选择 "属性"，在 "生成" 选项卡中勾选 "启用生成 XML 文档文件"，
            // 并指定生成的 XML 文件的路径。请注意确保该 XML 文件存在，并与程序集名称一致。
            var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
            var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
            option.IncludeXmlComments(xmlPath, true);

            // 对action的名称进行排序
            option.OrderActionsBy(o => o.RelativePath);

            // 可以在这里添加其他 Swagger 相关配置，例如添加身份验证信息等
        });
    }

    /// <summary>
    /// UseKnife4UI 中间件生效
    /// </summary>
    /// <param name="app"></param>
    public static void UseKnife4UiExt(this WebApplication app)
    {
        app.UseSwagger();
        // app.UseSwaggerUI();
        app.UseKnife4UI(option =>
        {
            foreach (string version in typeof(ApiVersion).GetEnumNames())
            {
                option.SwaggerEndpoint($"/swagger/{version}/swagger.json", $"Ellwood API {version}");
            }
            option.RoutePrefix = ""; // 路由前缀
        });
    }

} 